<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="shortcut icon" href="/img/favicon.webp">
    <link rel="stylesheet" href="/bootstrap-4.6.2-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/bootstrap-switch/bootstrap-switch.css">
    <link rel="stylesheet" href="/bootstrap-fileinput-master/css/fileinput.css">

    <script type="text/javascript" src="/js/jquery-3.5.1.min.js"></script>
    <script src="/bootstrap-4.6.2-dist/js/bootstrap.min.js"></script>
    <script src="/bootstrap-switch/bootstrap-switch.min.js"></script>
    <script src="/bootstrap-fileinput-master/js/fileinput.js"></script>
    <script src="/bootstrap-fileinput-master/js/locales/zh.js"></script>

    <script src="/js/page.js"></script>
    <style type="text/css">
        .static{
            padding: 1rem;
        }
        form.search input,form select{

        }
        .file-input.file-input-new{
            display: inline-block;
        }
        .file-input.file-input-new .input-group{
            top: 4px;
        }

        .file-caption-name{
            cursor: pointer;
        }

        .timer-switch{
            font-size: 10px;
            color: #6c757d;
        }
        .bootstrap-switch .bootstrap-switch-handle-off,
        .bootstrap-switch .bootstrap-switch-handle-on,
        .bootstrap-switch .bootstrap-switch-label{
            line-height: 35px;
            padding: 0px;
            width: 50px;
        }
        .bootstrap-switch .bootstrap-switch-label{
            background: url("/img/refresh-close.png");
            background-size: 45% 50%;
            background-repeat: no-repeat;
            background-position: 45% 50%;
        }
        .bootstrap-switch .bootstrap-switch-label.active{
            background: url("/img/refresh-open.png");
            background-size: 45% 50%;
            background-repeat: no-repeat;
            background-position: 45% 50%;
        }

        .rows .cards .card{
            width: 18rem;
            display: inline-block;
            margin: 5px 10px;
            text-align: left;
            background: url("/img/favicon.webp");
            background-size: 100% 100%;
            background-repeat: no-repeat;
            background-image: none;
        }

        .rows .cards .card .card-body p{
            height: 24px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 7px;
        }
        .rows .cards .card .virtual-status {
            text-decoration-style: dashed;
            text-decoration-line: underline;
            text-underline-offset: 5px;
        }

        .rows .card .card-body .checkbox{
            float: right;
        }
        .rows .cards .card span.disabled{
            cursor: no-drop;
        }


        .rows .cards .card .btn.disabled{
            pointer-events: none;
        }
        .rows .pagination{
            float: right;
        }
        .pagination .page-item.active:first-child .page-link.prev{
            background-color: #929497;
            cursor: no-drop;
            border-color: #929497;
        }
        .pagination .page-item.active:last-child .page-link.next{
            background-color: #929497;
            cursor: no-drop;
            border-color: #929497;
        }
        .pagination .page-item{
            cursor: pointer;
        }

        .rows .pagination-lg .page-link {
            font-size: 1rem;
            line-height: 1.5;
            padding: 0.55rem 1rem;
        }
    </style>
</head>

<script>
    $(function () {
        event();
        search(1);
    });



    var timer;
    function refresh(status) {
        if(status && !timer){
            timer = setInterval(function () {
                search(1);
            },5000)
        }else {
            clearInterval(timer);
            timer = 0;
        }
    }
    function event() {

        //上传
        $("#upload").fileinput({
            uploadUrl: "/device/crossEnvironmentUploadSwitch",
            language :'zh',
            browseClass : "btn btn-sm btn-dark",
            showRemove : false,  //显示移除按钮
            showPreview : false,  //是否显示预览
            showUpload : false,//选择完成后直接上传
        }).on("fileuploaded", function (event, data, previewId, index) {
           $(".kv-upload-progress").hide();
        });

        $(".file-caption-name").attr("placeholder","模板 点击下载....");
        $(".hidden-xs").text("导入启动....");


        $(".file-caption-name").on("click",function () {
            var ajax = new XMLHttpRequest();
            ajax.withCredentials = true;
            ajax.responseType = "blob";
            var fileName = "模板.xlsx";
            ajax.open('post','/device/download?fileName=' +  fileName);
            ajax.setRequestHeader("Content-Type","application/json;charset=utf-8");
            ajax.send(JSON.stringify({}));
            ajax.onreadystatechange = function () {
                if (ajax.readyState==4 &&ajax.status==200) {
                    var href = URL.createObjectURL(ajax.response);
                    var a = document.createElement('a');
                    a.setAttribute('href', href);
                    a.setAttribute('download', fileName);
                    a.click();
                    URL.revokeObjectURL(href);
                }
            }
        });

        //回车查询
        $("#query").on("keydown", "input:text", function (event) {
            if (event.keyCode == 13) {
                search(1);
            }
        });
        //按钮查询
        $("#query").on("click", "#search", function () {
            search(1);
        });

        //s实时刷新
        $('#timerSwitch').bootstrapSwitch({
            state: false,//开关状态
            size: null,//尺寸 mini small large
            animate: true,//开启动画效果
            disabled: false,//禁用
            readonly: false,
            indeterminate: false,
            inverse: false,//方向反转
            radioAllOff: false,
            onColor: 'success',//开启颜色 primary、info，primary，warning，warning，default
            offColor: 'warning',//关闭颜色 primary、info，primary，warning，warning，default
            onText: 'ON',//开启时展示的文本
            offText: 'OFF',//关闭时展示的文本
            labelText: '&nbsp',//空白区域的文本
            handleWidth: 'auto',
            labelWidth: 'auto',
            baseClass: 'bootstrap-switch',
            wrapperClass: 'wrapper',
            onInit: function onInit() { },
            onSwitchChange: function onSwitchChange(event,state) {
                $(".bootstrap-switch-label").toggleClass("active");
                refresh(state);
            }
        })


        //单个启动
        $(".cards").on("click", "[name='start']", function (event) {
            var deviceVal = $(event.target).parents(".card-body").find("input[name='device']").val();
            var device = JSON.parse(deviceVal);
            var query = getQueryForm();
            query.status = 1;
            switchStatus({query: query,devices:[device]});
            return false;
        });

        //单个停止
        $(".cards").on("click", "[name='stop']", function (event) {
            var deviceVal = $(event.target).parents(".card-body").find("input[name='device']").val();
            var device = JSON.parse(deviceVal);
            var query = getQueryForm();
            query.status = 2;
            switchStatus({query: query,devices:[device]});
            return false;
        });

        //查询批量启动
        $("#query").on("click", "#searchStart", function (event) {
            var query = getQueryForm();
            query.status = 1;
            switchStatus({query: query});
            return false;
        });

        //查询批量停止
        $("#query").on("click","#searchStop",function (event) {
            var query = getQueryForm();
            query.status = 2;
            switchStatus({query:query});
            return false;
        });

        //选中批量启动
        $("#query").on("click", "#checkStart", function (event) {
            var devices =  $(".cards").find("[name='device']:checked").map(function (item) { return  JSON.parse($(this).val()); });
            var query = getQueryForm();
            query.status = 1;
            switchStatus({query: query, devices:$.makeArray(devices)});
            return false;
        });
        //选中批量停止
        $("#query").on("click", "#checkStop", function (event) {
            var devices =  $(".cards").find("[name='device']:checked").map(function (item) { return  JSON.parse($(this).val()); });
            var query = getQueryForm();
            query.status = 2;
            switchStatus({query: query, devices:$.makeArray(devices)});
            return false;
        });
    }




    function search (pageNumber) {
        var param = getQueryForm();
        param.ts = new Date().getTime();
        param.pageNumber = pageNumber ? pageNumber : 1;
        param.pageSize = 15;

        $.ajax({
            type: "post",
            dataType: "json",
            url: '/device/crossEnvironmentPage',
            data: param,
            success: function (response) {
                if (!response || !response.data || !response.data.records || !response.data.total){
                    $(".cards").html("");
                    var pageSize = response && response.data && response.data.pageSize ? response.data.pageSize : 30;
                    pagination(0,pageSize,1);
                }else {
                    $(".cards").html(cardBuilder(response.data.records));
                }

                if(!response.data.pageNumber || response.data.pageNumber <= 1){
                    pagination(response.data.total,response.data.pageSize,response.data.pageNumber);
                }
            }
        });
    }

    function switchStatus (param) {
        $.ajax({
            type: "post",
            dataType: "json",
            contentType : "application/json",
            url: '/device/crossEnvironmentSwitch',
            data: JSON.stringify(param),
            success: function (response) {
                if (response && !response.status){
                    if(response.msg){
                        alert(response.msg);
                    }
                };

            }
        });
    }

    function getQueryForm() {
        var pid = $("#query #pid").val();
        var cid = $("#query #cid").val();

        var active = $("#query #active").val();
        var protocol = $("#query #protocol").val();
        var host = $("#query #host").val();
        var port = $("#query #port").val();
        var secretKey = $("#query #secretKey").val();

        return {"pid":pid,"cid":cid,"secretKey":secretKey,"active":active,"protocol":protocol,"host":host,"port":port};
    }



    function pagination(total,pageSize, pageNumber) {
        var pages = (total % pageSize == 0 ? parseInt(total / pageSize) : parseInt(total / pageSize) + 1);
        $('#pagination').pagination({
            pages: pages, //总页数
            edges: 5,
            cssStyle: 'pagination-lg', //按纽大小pagination-lg或写入自定义css
            displayedPages: pageNumber, //显示几个
            onPageClick: function(pageNumber, event) {
                //点击时调用
                search(pageNumber);
            },
            onInit: function(getid) {
                //刷新时或初始化调用
            }
        });
    }

    function cardBuilder(records) {
        var platformDeviceStatus = {
            1 : "<span>未激活</span>",
            2 : "<span class='text-secondary'>离线</span>",
            3 : "<span class='text-success'>在线</span>",
        };
        var virtualDeviceStatus = {
            1 : "<span class='text-success'>在线</span>",
            2 : "<span>启动中</span>",
            3 : "<span class='text-secondary'>离线</span>",
        };
        if(!records || records.length < 1){ return ;}
        var template = "";
        for(var i = 0 ; i < records.length ; i++){
            var record = records[i];
            var device = JSON.stringify(record).replace(/\"/g,'\&quot;');
            template+='<div class="card">'
                +'<div class="card-body">'
                +'<input type="checkbox" name="device" value="'+device+'" class="checkbox" aria-label="Checkbox for following text input">'
                +'<h5 class="card-title">'+record.cid+'</h5>'
                +'<p class="card-text">产品：<span name="pid">'+record.pid+'</span></p>'
                +'<p class="card-text">在线时间：<span name="onlineTIme">'+record.lastOnlineTime+'</span></p>';

            if(record.describe){
                var statusHtml = "<span class='virtual-status text-danger alert-link' title='"+record.describe+"'>"+virtualDeviceStatus[record.virtualDeviceStatus]+"....</span>";
                template +='<p class="card-text" >状态：<span name="status">'+statusHtml+'</span></p>';
            }else {
                var statusHtml = "<span class='virtual-status' >"+virtualDeviceStatus[record.virtualDeviceStatus]+"</span>";
                template +='<p class="card-text">状态：<span name="status">'+statusHtml+'</span></p>';
            }
            template +='<p class="card-text" >协议：<span name="status">'+record.protocol+'</span></p>';
            template +='<p class="card-text" >环境：<span name="status">'+record.active+'</span></p>';
            template+='<span class="'+(record.virtualDeviceStatus != 3 ? 'disabled' : '')+' start"><a href="#" '+(record.virtualDeviceStatus != 3 ? 'disabled' : '')+' class="btn btn-primary '+(record.virtualDeviceStatus != 3 ? 'disabled' : '')+'  btn-success" name="start">启动</a></span>'
                +'<span class="'+(record.virtualDeviceStatus == 3 ? 'disabled' : '')+' stop"><a href="#" '+(record.virtualDeviceStatus == 3 ? 'disabled' : '')+' class="btn btn-primary '+(record.virtualDeviceStatus == 3 ? 'disabled' : '')+'  btn-dark float-right" name="stop">停止</a></span>'
                +'</div>'
                +'</div>';
        }
        return template;
    }

</script>
<body>
<div class="static">
    <div class="rows">
        <form  id="query">
            <div class="form-row">

                <div class="form-group mr-sm-2">
                    <input type="text" class="form-control mb-2 mr-sm-2" id="active" placeholder="环境">
                </div>

                <div class="form-group mr-sm-2 col-md-1">
                    <select class="form-control mb-2 mr-sm-2" id="protocol">
                        <option selected>BRIDGE</option>
                        <option value="1">MQTT</option>
                    </select>
                </div>

                <div class="form-group mr-sm-2">
                    <input type="text" class="form-control mb-2 mr-sm-2" id="host" placeholder="HOST">

                </div>

                <div class="form-group mr-sm-2">
                    <input type="text" class="form-control mb-2 mr-sm-2" id="port" placeholder="PORT">
                </div>

                <div class="form-group mr-sm-2">
                    <label class="sr-only" for="pid">产品ID</label>
                    <input type="text" class="form-control mb-2 mr-sm-2" id="pid" placeholder="产品ID">
                </div>

                <div class="form-group mr-sm-2">
                    <input type="text" class="form-control mb-2 mr-sm-2" id="cid" placeholder="设备名">
                </div>

<!--
                <div class="form-group mr-sm-2">
                    <input type="text" class="form-control mb-2 mr-sm-2" id="secretKey" placeholder="秘钥">
                </div>
-->

                <div class="form-group mr-sm-2">
                    <a href="#" id="search" class="btn btn-info">查询</a>


                    <input type="file"  id="upload" class="btn btn-info"/>
                </div>


                <div class="form-group mr-sm-2">
                    <input type="checkbox" id="timerSwitch" class="form-control mb-2 mr-sm-2" checked>

                    <a href="#" id="searchStart" class="btn btn-primary btn-success">查询批量启动</a>
                    <a href="#" id="searchStop" class="btn btn-primary btn-dark">查询批量停止</a>

                    <a href="#" id="checkStart" class="btn btn-primary btn-success">选中批量启动</a>
                    <a href="#" id="checkStop" class="btn btn-primary btn-dark">选中批量停止</a>

                </div>



            </div>
        </form>
    </div>

    <div class="rows">
        <div class="cards"></div>
    </div>

    <div class="rows">
        <div class="pagination">
            <div id="pagination"></div>
        </div>
    </div>

</div>


</body>
</html>